# -*- coding: utf-8 -*-

import requests
import json

def translate_to_uyghur(text, app_key, access_token):
    """
    中文翻译为维吾尔语
    :param text: 要翻译的中文文本
    :param app_key: API密钥
    :param access_token: 访问令牌
    :return: 翻译结果
    """
    # API端点
    url = "https://open.xjguoyu.cn/api/core/1.0/mt"
    
    # 请求参数
    params = {
        'appKey': app_key
    }
    
    # 请求头
    headers = {
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': f'Bearer {access_token}',
        'Accept': 'application/json'
    }
    
    # 请求体
    data = {
        'text': text,
        'src': 'cn',
        'to': 'ug'
    }
    
    try:
        # 将数据转换为JSON字符串，并确保正确处理中文
        json_data = json.dumps(data, ensure_ascii=False)
        
        # 发送POST请求
        response = requests.post(
            url, 
            params=params, 
            headers=headers, 
            data=json_data.encode('utf-8'),  # 使用UTF-8编码
            verify=False
        )
        
        # 设置响应编码
        response.encoding = 'utf-8'
        
        if response.status_code == 200:
            return response.json()
        else:
            return {
                "error": f"请求失败，状态码：{response.status_code}",
                "response": response.text
            }
            
    except requests.exceptions.RequestException as e:
        return {"error": str(e)}
    except Exception as e:
        return {"error": f"发生未知错误: {str(e)}"}

# 使用示例
if __name__ == "__main__":
    APP_KEY = "ldxlVOlPTkF5qyKKNZxkkiBgu2qkFh47"
    ACCESS_TOKEN = "6d9ed85e9826e6de8b6a39cea81bba86" "xYXYcMmBeTDRGa6HQwPpRCieTfzbKcDZ"  # 需要替换为实际的access_token
    
    try:
        # 测试翻译
        chinese_text = "你好"
        print(f"正在翻译文本：{chinese_text}")
        
        result = translate_to_uyghur(chinese_text, APP_KEY, ACCESS_TOKEN)
        print("\n翻译结果：")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        
    except Exception as e:
        print(f"发生错误：{str(e)}")
